package com.ruoyi.prod.service.impl;

import java.util.List;
import com.ruoyi.common.core.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import com.ruoyi.common.core.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.prod.domain.Products;
import com.ruoyi.prod.mapper.BrandMapper;
import com.ruoyi.prod.domain.Brand;
import com.ruoyi.prod.service.IBrandService;

/**
 * 品牌Service业务层处理
 * 
 * @author nz
 * @date 2025-07-31
 */
@Service
public class BrandServiceImpl implements IBrandService 
{
    @Autowired
    private BrandMapper brandMapper;

    /**
     * 查询品牌
     * 
     * @param id 品牌主键
     * @return 品牌
     */
    @Override
    public Brand selectBrandById(Long id)
    {
        return brandMapper.selectBrandById(id);
    }

    /**
     * 查询品牌列表
     * 
     * @param brand 品牌
     * @return 品牌
     */
    @Override
    public List<Brand> selectBrandList(Brand brand)
    {
        return brandMapper.selectBrandList(brand);
    }

    /**
     * 新增品牌
     * 
     * @param brand 品牌
     * @return 结果
     */
    @Transactional
    @Override
    public int insertBrand(Brand brand)
    {
        brand.setCreateTime(DateUtils.getNowDate());
        int rows = brandMapper.insertBrand(brand);
        insertProducts(brand);
        return rows;
    }

    /**
     * 修改品牌
     * 
     * @param brand 品牌
     * @return 结果
     */
    @Transactional
    @Override
    public int updateBrand(Brand brand)
    {
        brand.setUpdateTime(DateUtils.getNowDate());
        brandMapper.deleteProductsByBrandId(brand.getId());
        insertProducts(brand);
        return brandMapper.updateBrand(brand);
    }

    /**
     * 批量删除品牌
     * 
     * @param ids 需要删除的品牌主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteBrandByIds(Long[] ids)
    {
        brandMapper.deleteProductsByBrandIds(ids);
        return brandMapper.deleteBrandByIds(ids);
    }

    /**
     * 删除品牌信息
     * 
     * @param id 品牌主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteBrandById(Long id)
    {
        brandMapper.deleteProductsByBrandId(id);
        return brandMapper.deleteBrandById(id);
    }

    /**
     * 新增商品信息信息
     * 
     * @param brand 品牌对象
     */
    public void insertProducts(Brand brand)
    {
        List<Products> productsList = brand.getProductsList();
        Long id = brand.getId();
        if (StringUtils.isNotNull(productsList))
        {
            List<Products> list = new ArrayList<Products>();
            for (Products products : productsList)
            {
                products.setBrandId(id);
                list.add(products);
            }
            if (list.size() > 0)
            {
                brandMapper.batchProducts(list);
            }
        }
    }
}
